import Index from '@/views/Index.vue'
import { createRouter, createWebHistory } from 'vue-router'
import useStore from '@/stores/index'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: Index,
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('@/views/main/Home.vue'),
        },
        {
          path: 'users',
          name: 'users',
          children: [
            {
              path: 'list',
              name: 'users-list',
              component: () => import('@/views/main/users/Users.vue'),
            },
          ],
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/Login.vue'),
      meta: {
        title: '登录',
      },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/login/Register.vue'),
      meta: {
        title: '注册',
      },
    },
  ],
})

router.beforeEach(async (to, from) => {
  const store = useStore()
  if (
    // 检查用户是否已登录
    !store.isLogin &&
    // ❗️ 避免无限重定向
    to.name !== 'login'
  ) {
    // 将用户重定向到登录页面
    return { name: 'login' }
  }
})

export default router
